//
//  ContentView.swift
//  Zapsh
//
//  Created by admin on 09.03.2024.
//

import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var items: [Item]

    var body: some View {
        HStack(spacing: 15) {
            DayForecast(day: "Понедельник", hight: "40", low: "13", isRainy: false)
            DayForecast(day: "Вторник", hight: "19", low: "-11", isRainy: true)
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(timestamp: Date())
            modelContext.insert(newItem)
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            for index in offsets {
                modelContext.delete(items[index])
            }
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: Item.self, inMemory: true)
}

struct DayForecast: View {
    let day: String
    let hight: String
    let low: String
    let isRainy: Bool
    
    var iconName: String {
        isRainy ? "cloud.rain.fill" : "sun.max.fill"
    }
    
    var iconColor: Color {
        isRainy ? .black : .yellow
    }
    
    var hightTextColor: Color {
        computeColor(hight)
    }
    
    var lowTextColor: Color {
        computeColor(low)
    }
    
    var body: some View {
        VStack() {
            Text(day)
                .font(.headline)
                .foregroundStyle(Color.white)
            Image(systemName: iconName)
                .foregroundStyle(iconColor)
                .font(.largeTitle)
                .padding(5)
            Text("Максимум: \(hight)")
                .fontWeight(Font.Weight.semibold)
                .foregroundStyle(hightTextColor)
            Text("Минимум: \(low)")
                .fontWeight(Font.Weight.medium)
                .foregroundStyle(lowTextColor)
        }
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 15)
                .foregroundColor(Color.indigo)
                .opacity(0.5)
                .shadow(radius: 15)
        )
    }
    
    private func computeColor(_ level: String) -> Color {
        let t = Double(level) ?? 0.0
        return t < 0 ? Color.black : ( t > 0 && t <= 21 ) ? Color.white : Color.yellow
    }
}
